require 'rake'

class Shell
  def initialize(args)
    @args = args
  end
  
  def run
    if @args.length > 0
      if invoke_targets(@args)
        exit(0)
      else
        exit(1)
      end
    else
      puts "jrake shell v0.0"
      prev_commands = ['help']      
      invoke_targets(prev_commands)
      loop do
        print 'jrake> '
        commands = $stdin.readline.split
        commands = prev_commands if commands.length == 0
        invoke_targets(commands)
        prev_commands = commands
      end
    end
  end
  
private

  def invoke_targets(target_names)
    load 'rakefile.rb'
    targets = target_names.map do |target_name| 
      target = Rake.application.lookup(target_name)
      if target.nil?
        puts "Target '#{target_name}' not found"
        return false
      end
      target
    end
    targets.each do |target|
      target.invoke
    end
    return true
  rescue => e
    puts e
    puts e.backtrace.join("\n")
    return false    
  ensure
    Rake.application.clear
  end
end

Shell.new(ARGV).run